﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;

namespace Equation.Enterprise.Framework.Windsor
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private IWindsorContainer container;

        public WindsorControllerFactory(IWindsorContainer container)
        {
            if (container ==null)
                throw new ArgumentNullException("The container cannot be null");
            this.container = container;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(0x194,
                                        string.Format(
                                            "The controller for path {0} could not be found or it does not implement IController",
                                            requestContext.HttpContext.Request.Path));
            }
            var controller = (IController) this.container.Resolve(controllerType);
            return controller;
        }

        public override void ReleaseController(IController controller)
        {
            var disposable = controller as IDisposable;
            if (disposable!=null)
                disposable.Dispose();

            this.container.Release(controller);
        }
    }
}
